package com.example.meitao.ui;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.webkit.WebView;
import android.widget.ProgressBar;

import com.example.meitao.R;
import com.example.meitao.client.MyChormeClient;
import com.example.meitao.client.MyWebViewClient;

public class NetQueryActivity extends AppCompatActivity {

    private Toolbar mToolbar;
    private WebView mWebView;
    private ProgressBar mProgressBar;
    private SearchView mSearchView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_net_query);
        initView();
        setData();
    }

    private void setData() {
        //加载网址
        mWebView.loadUrl("http://mmeitao.com/o");
        MyWebViewClient webViewClient = new MyWebViewClient();
        webViewClient.setClientListener(new MyWebViewClient.ClientCallBack() {
            @Override
            public void onStart(String url) {
                mProgressBar.setVisibility(View.VISIBLE);
            }

            @Override
            public void onFinish(String url) {
                mProgressBar.setVisibility(View.GONE);
            }
        });
        mWebView.setWebViewClient(webViewClient);

        //给WebView设置一个ChromeClient,来监测网页加载进度和收到的标题
        mWebView.setWebChromeClient(new MyChormeClient());
        MyChormeClient client = new MyChormeClient();
        client.setChormeListener(new MyChormeClient.ChormeCallBack() {
            @Override
            public void onProgressChanged(int progress) {
                mProgressBar.setProgress(progress);
            }

            @Override
            public void onReceivedTitle(String title) {
                if (!TextUtils.isEmpty(title)){
                    mToolbar.setTitle("");
                }
            }
        });

    }

    private void initView() {
        mToolbar = (Toolbar) findViewById(R.id.tl_net_search);
        setSupportActionBar(mToolbar);
        mWebView = (WebView)findViewById(R.id.wv_content);
        mProgressBar = (ProgressBar)findViewById(R.id.pb_net_show);
        mSearchView = (SearchView)findViewById(R.id.sv_net_url);
    }

    //当用户按下返回键的时候,系统自动调用这个方法
    @Override
    public void onBackPressed() {
        if(mWebView.canGoBack()) {
            mWebView.goBack();
        }else {
            super.onBackPressed();
        }
    }
}
